package com.yang.newRetail.initialize;

import com.alibaba.fastjson.JSON;
import com.yang.newRetail.global.Val;
import com.yang.newRetail.service.WebSocketService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Slf4j
@Component
public class WsApplicationRunnerImpl implements ApplicationRunner {

    @Autowired
    private Val val;

    /**
     * 用于指示bean包含在SpringApplication中时应运行的接口。可以定义多个ApplicationRunner bean
     * 在同一应用程序上下文中，可以使用有序接口或@order注释对其进行排序。
     */
    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("WsApplicationRunnerImpl init...");

        Set<String> optionNames = args.getOptionNames();
        for (String optionName : optionNames) {
            log.info("这是传过来的参数[{}]", optionName);
        }
        String[] sourceArgs = args.getSourceArgs();
        for (String sourceArg : sourceArgs) {
            log.info("这是传过来sourceArgs[{}]", sourceArg);
        }

        new Thread(()-> {
            while (true){
                Map<String, Object> result = null;
                try {
                    result = val.resultQueueTake();
                } catch (InterruptedException e) {
                    System.out.println("resultQueue take error");
                    throw new RuntimeException(e);
                }

                Map<String, Object> finalResult = new HashMap<>();
                finalResult.put("code", 1000);
                finalResult.put("message", JSON.toJSONString(result));

                WebSocketService.sendMessageByUser((Integer) result.get("userId"), JSON.toJSONString(finalResult));
            }
        }).start();
    }
}
